package com.wicket.okrcalc.biz.service.nb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wicket.okrapp.common.baseinfo.BaseInfoHolder;
import com.wicket.okrcalc.biz.service.dto.common.MemoryBusinessDataDto;
import com.wicket.okrcalc.biz.service.dto.common.MemoryBusinessResDataDto;
import com.wicket.okrcalc.biz.service.dto.res.*;
import com.wicket.okrcalc.common.util.CommonFunctionHelper;
import com.wicket.okrcalc.integration.dto.DataBigMiniRecordDto;
import com.wicket.okrcomponent.common.exception.BizException;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Tags;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.stereotype.Service;
import com.wicket.okrcalc.biz.service.dto.req.ImplementBizBusinessFieldPushMemoryReqDto;
import com.wicket.okrcalc.biz.service.dto.req.ObtainGetPublicFieldCacheReqDto;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.wicket.okrcalc.biz.service.dto.req.ImplementMultiplyTwoValuesReqDto;
import com.wicket.okrcalc.biz.service.dto.req.CalculateDataBigMiniRecordNewReqDto;
import com.wicket.okrcalc.biz.service.dto.req.ImplementDashboardReceiveFieldReqDto;
import com.wicket.okrcalc.biz.service.dto.req.AddCalcMemoryBusinessDataReqDto;
import com.wicket.okrcalc.biz.service.dto.req.QueryCalcMemoryBusinessDataDetailReqDto;
import com.wicket.okrcalc.biz.service.dto.req.ImplementSpaceConfPushMemoryCalcReqDto;

/**
 * @author ： 手工接入方法
 * @since 2022/5/28 15:32
 *
 *
 * @version 1.0
 */
@Service
public class NbInterfaceMode {
/**
      * code:publicFieldCache
      * name:M4-执行业务应用业务字段推送内存（特殊方法）
      * desc:undefined
      * gen by moon at 12/4/2022, 3:10:16 AM
      * 
      **/
     @Trace(operationName = "M4-执行业务应用业务字段推送内存（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public ImplementBizBusinessFieldPushMemoryRespDto implementBizBusinessFieldPushMemory(ImplementBizBusinessFieldPushMemoryReqDto reqDto) {
         ImplementBizBusinessFieldPushMemoryRespDto retData = new ImplementBizBusinessFieldPushMemoryRespDto();
         JSONObject retJson = new JSONObject();
         Field[] declaredFields = reqDto.getClass().getDeclaredFields();
         for(Field field : declaredFields){
             field.setAccessible(true);
             try {
                 Object value = field.get(reqDto);
                 if(ObjectUtils.isNotEmpty(value)){
                     retJson.put(field.getName(),value);
                 }
             } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
         }
         CommonFunctionHelper.getBaseInfoFromLocal().setBusinessData(retJson.toJSONString());
        return retData;
      }
/**
      * code:getPublicFieldCache
      * name:M4-获取内存中业务字段（特殊方法）
      * desc:undefined
      * gen by moon at 12/4/2022, 3:13:54 AM
      * 
      **/
     @Trace(operationName = "M4-获取内存中业务字段（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public ObtainGetPublicFieldCacheRespDto obtainGetPublicFieldCache(ObtainGetPublicFieldCacheReqDto reqDto) {
         ObtainGetPublicFieldCacheRespDto retData = new ObtainGetPublicFieldCacheRespDto();
         String businessData = CommonFunctionHelper.getBaseInfoFromLocal().getBusinessData();
         JSONObject localDataJson = JSONObject.parseObject(businessData);
         Field[] declaredFields = retData.getClass().getDeclaredFields();
         for(Field field : declaredFields){
             field.setAccessible(true);
             try {
                 if(ObjectUtils.isNotEmpty(localDataJson.get(field.getName()))){
                     if(field.getType().equals(Long.class)){
                         field.set(retData,Long.valueOf((String)localDataJson.get(field.getName())));
                     }else if(field.getType().equals(Date.class)){
                         Date tmpDate = new Date(Long.valueOf(localDataJson.getString(field.getName())));
                         field.set(retData,tmpDate);
                     }else{
                         field.set(retData,localDataJson.get(field.getName()));
                     }

                 }
             } catch (IllegalAccessException e) {
                 e.printStackTrace();
             }
         }
         return retData;
      }
/**
      * code:multiOfTwoNum
      * name:M2执行两个数值相乘（特殊方法）
      * desc:undefined
      * gen by moon at 12/11/2022, 3:38:51 AM
      *
      **/
     @Trace(operationName = "M2执行两个数值相乘（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public ImplementMultiplyTwoValuesRespDto implementMultiplyTwoValues(ImplementMultiplyTwoValuesReqDto reqDto) {
         ImplementMultiplyTwoValuesRespDto retData = new ImplementMultiplyTwoValuesRespDto();

         int mode = BigDecimal.ROUND_HALF_UP;
         if(reqDto.getDecimalDigitsLastRules().equals("MALING")){
             mode = BigDecimal.ROUND_DOWN;
         }

         if (reqDto.getComFloatField1() == null || reqDto.getComFloatField2() == null) {
             return retData;
         }

         BigDecimal param1 = new BigDecimal(reqDto.getComFloatField1().toString());
         BigDecimal param2 = new BigDecimal(reqDto.getComFloatField2().toString());

         BigDecimal result = param1.multiply(param2);
         result = result.setScale(reqDto.getDecimalPointRules().intValue(),mode);
         retData.setCalcResult(result.doubleValue());
         return retData;
      }

    public static void main(String[] args) {
        NbInterfaceMode o = new NbInterfaceMode();
        ImplementMultiplyTwoValuesReqDto req = new ImplementMultiplyTwoValuesReqDto();
        req.setDecimalPointRules(2L);
        req.setDecimalDigitsLastRules("MALING");
        req.setComFloatField1(60.0);
        req.setComFloatField2(0.01);
        ImplementMultiplyTwoValuesRespDto ret = o.implementMultiplyTwoValues(req);
        System.out.println(ret);
    }
/**
      * code:maxOrMinOfMultipleNum
      * name:M4-计算数据集最大小值记录（特殊方法）
      * desc:undefined
      * gen by moon at 2/26/2023, 5:11:11 PM
      * 
      **/
     @Trace(operationName = "M4-计算数据集最大小值记录（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public CalculateDataBigMiniRecordNewRespDto calculateDataBigMiniRecordNew(CalculateDataBigMiniRecordNewReqDto reqDto) {
         CalculateDataBigMiniRecordNewRespDto retData = new CalculateDataBigMiniRecordNewRespDto();
         com.wicket.okrcalc.integration.dto.DataBigMiniRecordDto max = new com.wicket.okrcalc.integration.dto.DataBigMiniRecordDto();
         com.wicket.okrcalc.integration.dto.DataBigMiniRecordDto min = new DataBigMiniRecordDto();
         int mode = -1;
         if(reqDto.getDecimalDigitsLastRules()!=null){
             mode = BigDecimal.ROUND_HALF_UP;
             if(reqDto.getDecimalDigitsLastRules().equals("MALING")){
                 mode = BigDecimal.ROUND_DOWN;
             }
         }
         if(CollectionUtil.isEmpty(reqDto.getDataBigMiniRecordList())){
             return retData;
         }
         for(com.wicket.okrcalc.integration.dto.DataBigMiniRecordDto one : reqDto.getDataBigMiniRecordList()){
             if(reqDto.getCalcMaxAndMin().equals("MAX")){
                 if(max.getComFloatField1()==null){
                     max = one;
                 }else{
                     if(one.getComFloatField1().doubleValue() > max.getComFloatField1().doubleValue()){
                         max = one;
                     }
                 }
             }else if(reqDto.getCalcMaxAndMin().equals("MIN")){
                 if(min.getComFloatField1()==null){
                     min = one;
                 }else{
                     if(one.getComFloatField1().doubleValue() < min.getComFloatField1().doubleValue()){
                         min = one;
                     }
                 }
             }
         }
         if(reqDto.getCalcMaxAndMin().equals("MAX")){
             BigDecimal result = new BigDecimal(max.getComFloatField1());
             if(mode!=-1){
                 result = result.setScale(reqDto.getDecimalPointRules().intValue(),mode);
             }
             retData.setCommPrimaryKey(max.getCommPrimaryKey());
             retData.setComFloatField1(result.doubleValue());
         }else if(reqDto.getCalcMaxAndMin().equals("MIN")){
             BigDecimal result = new BigDecimal(min.getComFloatField1());
             if(mode!=-1){
                 result = result.setScale(reqDto.getDecimalPointRules().intValue(),mode);
             }
             retData.setCommPrimaryKey(min.getCommPrimaryKey());
             retData.setComFloatField1(result.doubleValue());
         }
         return retData;
      }
/**
      * code:receptionService
      * name:M4执行大屏接收字段
      * desc:undefined
      * gen by moon at 3/29/2024, 8:55:06 PM
      *
      **/
     @Trace(operationName = "M4执行大屏接收字段")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public ImplementDashboardReceiveFieldRespDto implementDashboardReceiveField(ImplementDashboardReceiveFieldReqDto reqDto) {
         return BeanUtil.toBean(reqDto, ImplementDashboardReceiveFieldRespDto.class);
      }
/**
      * code:addMemoryBusinessData
      * name:M4新增内存业务数据（特殊方法）
      * desc:undefined
      * gen by moon at 5/19/2024, 2:14:00 AM
      *
      **/
     @Trace(operationName = "M4新增内存业务数据（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public AddCalcMemoryBusinessDataRespDto addCalcMemoryBusinessData(AddCalcMemoryBusinessDataReqDto reqDto) {
         String key = reqDto.getBusinessDataObject() + "_" +reqDto.getDataObjectBatchCode();
         JSONObject objectData = new JSONObject();
         for(MemoryBusinessDataDto one : reqDto.getMemoryBusinessDataList()){
             objectData.put(one.getFieldName(),one.getFieldValue());
         }
         if(reqDto.getIsDataList().equals("TRUE")){
             Object currentData = CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().get(key);
             if(currentData!=null){
                 if(currentData instanceof JSONArray){
                     JSONArray arrayData = (JSONArray)currentData;
                     arrayData.add(objectData);
                     CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key,arrayData);
                 }else{
                     throw new BizException("-1","想取数据集，但是存的是对象",false);
                 }
             }else{
                 JSONArray arrayData = new JSONArray();
                 arrayData.add(objectData);
                 CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key,arrayData);
             }
         }else{
             CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().put(key,objectData);
         }
         return new AddCalcMemoryBusinessDataRespDto();
      }
/**
      * code:queryMemoryBusinessData
      * name:M4查询内存业务数据详情（特殊方法）
      * desc:undefined
      * gen by moon at 5/19/2024, 2:15:18 AM
      *
      **/
     @Trace(operationName = "M4查询内存业务数据详情（特殊方法）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public QueryCalcMemoryBusinessDataDetailRespDto queryCalcMemoryBusinessDataDetail(QueryCalcMemoryBusinessDataDetailReqDto reqDto) {
         QueryCalcMemoryBusinessDataDetailRespDto retData = new QueryCalcMemoryBusinessDataDetailRespDto();
         String key = reqDto.getBusinessDataObject() + "_" +reqDto.getDataObjectBatchCode();
         JSONObject currentData = (JSONObject) CommonFunctionHelper.getBaseInfoFromLocal().getLocalCachePool().get(key);
         if(currentData==null){
             return retData;
         }

         Map<String, Field> fieldIndex = new HashMap<>();
         Field[] fields = QueryCalcMemoryBusinessDataDetailRespDto.class.getDeclaredFields();
         for(Field one : fields){
             one.setAccessible(true);
             fieldIndex.put(one.getName(),one);
         }


         for(MemoryBusinessResDataDto one : reqDto.getMemoryBusinessResDataList()){
             Object value = currentData.get(one.getFieldName());
             Field field = fieldIndex.get(one.getFieldValue());
             if(value!=null){
                 try {
                     field.set(retData,String.valueOf(value));
                 } catch (IllegalAccessException e) {
                     e.printStackTrace();
                 }
             }
         }
         return retData;
     }
/**
      * code:publicFieldCache
      * name:M4执行空间配置推送内存（CALC）
      * desc:undefined
      * gen by moon at 5/19/2024, 2:37:43 PM
      *
      **/
     @Trace(operationName = "M4执行空间配置推送内存（CALC）")
     @Tags({@Tag(key = "参数",value = "arg[0]"),
     @Tag(key = "返回值",value = "returnedObj")})
      public ImplementSpaceConfPushMemoryCalcRespDto implementSpaceConfPushMemoryCalc(ImplementSpaceConfPushMemoryCalcReqDto reqDto) {
         com.wicket.okrcalc.common.baseinfo.BaseInfoDO domain = new com.wicket.okrcalc.common.baseinfo.BaseInfoDO();
         if(BaseInfoHolder.contextHolder.get()!=null){
             BeanUtil.copyProperties(BaseInfoHolder.contextHolder.get().getBaseInfo(),domain);
             BaseInfoHolder.contextHolder.remove();
         }
         if(reqDto.getSpaceId()!=null){
             domain.setSpecSpaceId(reqDto.getSpaceId());
         }

         if(reqDto.getSpaceId()!=null){
             domain.setSpecInductionRecordId(reqDto.getSpaceId());
         }

         if(reqDto.getFileDisplayRootPath()!=null){
             domain.setFileDisplayRootPath(reqDto.getFileDisplayRootPath());
         }

         com.wicket.okrcalc.common.util.CommonFunctionHelper.setBaseInfoToLocal(domain);
         return new ImplementSpaceConfPushMemoryCalcRespDto();
     }

//    @Trace(operationName = "组装sql")
//    @Tags({@Tag(key = "参数",value = "arg[0]"),
//            @Tag(key = "返回值",value = "returnedObj")})
//    public String buildSql(ImplementGeneralSubsectionQueryBusinessDataReqDto reqDto){
//
//        Map<String,String> queryKey = new HashMap<>();
//
//        Map<String, Date> timeQueryKey = new HashMap<>();
//
//        Map<String, String> timeQueryRuleKey = new HashMap<>();
//        if(reqDto.getRefCustomField1()!=null && reqDto.getRefCustomFieldValue1()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField1()),reqDto.getRefCustomFieldValue1());
//        }
//
//        if(reqDto.getRefCustomField2()!=null && reqDto.getRefCustomFieldValue2()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField2()),reqDto.getRefCustomFieldValue2());
//        }
//
//        if(reqDto.getRefCustomField3()!=null && reqDto.getRefCustomFieldValue3()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField3()),reqDto.getRefCustomFieldValue3());
//        }
//
//        if(reqDto.getRefCustomField4()!=null && reqDto.getRefCustomFieldValue4()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField4()),reqDto.getRefCustomFieldValue4());
//        }
//
//        if(reqDto.getRefCustomField5()!=null && reqDto.getRefCustomFieldValue5()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField5()),reqDto.getRefCustomFieldValue5());
//        }
//
//        if(reqDto.getRefCustomField6()!=null && reqDto.getRefCustomFieldValue6()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField6()),reqDto.getRefCustomFieldValue6());
//        }
//
//        if(reqDto.getRefCustomField7()!=null && reqDto.getRefCustomFieldValue7()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField7()),reqDto.getRefCustomFieldValue7());
//        }
//
//        if(reqDto.getRefCustomField8()!=null && reqDto.getRefCustomFieldValue8()!=null){
//            queryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getRefCustomField8()),reqDto.getRefCustomFieldValue8());
//        }
//
//        if(reqDto.getComTimeFieldName1()!=null && reqDto.getComTimeFieldValue1()!=null){
//            timeQueryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName1()),reqDto.getComTimeFieldValue1());
//            timeQueryRuleKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName1()),reqDto.getComTimeFieldRule1());
//        }
//
//        if(reqDto.getComTimeFieldName2()!=null && reqDto.getComTimeFieldValue2()!=null){
//            timeQueryKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName2()),reqDto.getComTimeFieldValue2());
//            timeQueryRuleKey.put(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getComTimeFieldName2()),reqDto.getComTimeFieldRule2());
//        }
//
//        StringBuilder where = new StringBuilder();
//        if (!queryKey.isEmpty() || !timeQueryKey.isEmpty()) {
//            where.append(" WHERE ");
//            for (Map.Entry<String, String> entry : queryKey.entrySet()) {
//                String key = entry.getKey();
//                String value = entry.getValue();
//                where.append(key).append(" = ").append("'").append(value).append("'").append(" AND ");
//            }
//
//            for (Map.Entry<String, Date> entry : timeQueryKey.entrySet()) {
//                String key = entry.getKey();
//                String value = DateTimeUtil.dateFormat(entry.getValue());
//                String rule = timeQueryRuleKey.get(entry.getKey());
//                if(rule.equals("=")){
//                    where.append(key).append(" = ").append("'").append(value).append("'").append(" AND ");
//                }else if(rule.equals(">")){
//                    where.append(key).append(" > ").append("'").append(value).append("'").append(" AND ");
//                }else if(rule.equals("<")){
//                    where.append(key).append(" < ").append("'").append(value).append("'").append(" AND ");
//                }else if(rule.equals(">=")){
//                    where.append(key).append(" >= ").append("'").append(value).append("'").append(" AND ");
//                }else if(rule.equals("<=")){
//                    where.append(key).append(" <= ").append("'").append(value).append("'").append(" AND ");
//                }
//            }
//
//            if(reqDto.getBusinessDataSetPrimaryKeyName()!=null
//                    && !reqDto.getBusinessDataSetPrimaryKeyName().isEmpty()
//                    && reqDto.getLastDataObjectId()!=null
//                    && !reqDto.getLastDataObjectId().isEmpty()){
//                where.append(com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getOrderFieldName())).append(" > ").append("'").append(reqDto.getLastDataObjectId()).append("'").append(" AND ");
//            }
//            where.delete(where.length() - 5, where.length());
//        }
//
//        StringBuilder orderBy = new StringBuilder();
//        if(reqDto.getOrderFieldName()!=null){
//            orderBy.append(" order by " + com.wicket.okrapp.common.util.CommonFunctionHelper.humpToUnderline(reqDto.getOrderFieldName()));
//        }
//
//        if(reqDto.getOrderRule()!=null && reqDto.getOrderRule().equals("FROM_LARGE_TO_SMALL")){
//            orderBy.append(" desc ");
//        }else if(reqDto.getOrderRule()!=null && reqDto.getOrderRule().equals("FROM_SMALL_TO_LARGE")){
//            orderBy.append(" asc ");
//        }
//
//        StringBuilder limit = new StringBuilder();
//        if(reqDto.getDatasNum()!=null){
//            limit.append(" limit " + reqDto.getDatasNum());
//        }
//
//
//        String selectPreFixStr = "SELECT * FROM " + reqDto.getBusinessDataSetTableName() + " ";
//        String sql = selectPreFixStr + where.toString() + orderBy.toString() + limit.toString();
//        return sql;
//      }
  //手工接入方法
}
